package org.zn.etl.job.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhounan
 * @date 2025年1月14日
 * @description
 */
public class StateOfRWBuffer<T> {

	/**
	 * 0 preparing , 1 ready ,2 canWrite ,-1 closed
	 */
	private AtomicInteger state;

	private List<T> writeData;
	private List<T> readData;

	private Integer size;

	public StateOfRWBuffer(Integer size) {
		this.size = size;
		writeData = new ArrayList<>(size);
		state=new AtomicInteger(2);
	}

	public void doWrite() {
		state.updateAndGet(i -> 0);
	}

	public void add(T t) {
		writeData.add(t);
	}

	public void addAll(List<T> t) {
		writeData.addAll(t);
	}

	public void ready() {
		readData = writeData;
		writeData = new ArrayList<>(size);
		state.updateAndGet(i -> 1);
	}

	public List<T> getReadData() {
		return readData;
	}
	
	public void readed() {
		state.updateAndGet(i -> 2);
	}

	public boolean canRead() {
		return  Objects.equals(state.get(), 1) ;
	}

	public boolean canWrite() {
		return Objects.equals(state.get(), 2);
	}

	public void waitToRead() throws InterruptedException {

		while (!state.compareAndSet(1, 1)) {		
			
		}
		
	}

	public void waitToWrite() throws InterruptedException {
		
		while (!state.compareAndSet(2, 0)) {
		}

	}

	public void close() {
		state.updateAndGet(i -> -1);
	}

	public boolean isClosed() {

		return Objects.equals(state.get(), -1);

	}

}
